package org.cfd.controller;

import jakarta.annotation.Resource;
import java.util.List;
import org.cfd.entity.Carts;
import org.cfd.service.CartsService;
import org.cfd.utils.Code;
import org.cfd.utils.Result;
import org.springframework.web.bind.annotation.*;

/**
 * 购物车控制器类
 *
 * @author rjs
 */
@RestController
@CrossOrigin
@RequestMapping("/cart")
public class CartController {

  /** 购物车服务类 */
  @Resource private CartsService cartsService;

  /**
   * 保存购物车
   *
   * @param carts 购物车对象
   * @return 返回保存结果的Result对象
   */
  @PostMapping
  public Result save(@RequestBody Carts carts) {
    if (cartsService.save(carts)) {
      return new Result(Code.ADD_SUCCESS, "购物车保存成功");
    } else {
      return new Result(Code.ADD_ERROR, "购物车保存失败");
    }
  }

  /**
   * 根据用户ID获取购物车
   *
   * @param id 用户ID
   * @return 返回获取结果的Result对象
   */
  @GetMapping("/{id}")
  public Result getByUserId(@PathVariable Integer id) {
    List<Carts> cartsInfo = cartsService.getCartsByUserId(id);
    if (cartsInfo.isEmpty()) {
      return new Result(Code.SELECT_ERROR, "购物车查询失败");
    } else {
      return new Result(Code.SELECT_SUCCESS, "购物车查询成功", cartsInfo);
    }
  }

  /**
   * 更新购物车
   *
   * @param carts 购物车对象
   * @return 返回更新结果的Result对象
   */
  @PutMapping
  public Result updateCart(@RequestBody Carts carts) {
    cartsService.updateById(carts);
    Carts cartInfo = cartsService.getById(carts.getId());
    if (cartInfo != null) {
      return new Result(Code.UPDATE_SUCCESS, "购物车更新成功");
    } else {
      return new Result(Code.UPDATE_ERROR, "购物车更新失败");
    }
  }

  /**
   * 根据购物车ID删除购物车
   *
   * @param id 购物车ID
   * @return 返回删除结果的Result对象
   */
  @DeleteMapping("/{id}")
  public Result deleteByCartsId(@PathVariable Integer id) {
    if (cartsService.removeById(id)) {
      return new Result(Code.DELETE_SUCCESS, "购物车删除成功");
    } else {
      return new Result(Code.DELETE_ERROR, "购物车删除失败");
    }
  }
}
